using System;
using System.Text;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Web;

using Framework;

namespace SchemaMonitor
{
    //Collection Class (Customisable half)
    public partial class CTagTypeList
    {
		#region Filters
		public CTagTypeList OneToOne { get { return GetByAgIsOneToOne(true); } }
		public CTagTypeList OneToMany { get { return GetByAgIsOneToOne(false); } }
		public CMetaTagList Tags
		{
			get
			{
				var list = new CMetaTagList();
				foreach (var i in this)
					list.AddRange(i.MetaTags);
				return list;
			}
		}

		public CTagType FB_Filters { get { return GetOrCreate("Unsafe", FB.AppId, true); } }
		public CTagType FB_PostRating { get { return GetOrCreate("Rating", FB.AppId, true); } }
		public CTagType FB_Album { get { return GetOrCreate("Album", FB.AppId); } }
		public CTagType FB_Post { get { return GetOrCreate("Post", FB.AppId); } }
		private CApp FB { get { return CApp.Cache.Facebook; } }
		public CTagType GetOrCreate(string name, int appId, bool oneToOne = false)
		{
			foreach (var i in this.GetByAppId(appId))
				if (i.TypeName.ToLower() == name.ToLower())
					return i;
			var a = new CTagType();
			a.TypeAppId = appId;
			a.TypeName = name;
			a.TagIsOneToOne = oneToOne;
			a.Save();
			return a;
		}
		#endregion

		#region Aggregation
		#endregion

		#region Searching (Optional)
		//Represents a simple search box to search PK and any string columns (add overloads as required, based on the pattern below)
		//e.g. public CTagTypeList Search(string nameOrId, int ypeAppId, bool? agIsOneToOne) { ...
		public CTagTypeList Search(string nameOrId)
        {
            //1. Normalisation
            nameOrId = (nameOrId??string.Empty).Trim().ToLower();
            
            //2. Start with a complete list
            CTagTypeList results = this;
            
            //3. Use any available index, such as those generated for fk/bool columns
            //Normal Case - non-unique index (e.g. foreign key)
            //if (int.MinValue != ypeAppId) results = results.GetByypeAppId(ypeAppId);
            //if (agIsOneToOne.HasValue)   results = results.GetByagIsOneToOne(agIsOneToOne.Value); //Customise bool filters according to UI (e.g. for checkbox, use simple bool and bias in one direction)

            //Special case - unique index (e.g. primary key)
            /*
            if (!string.IsNullOrEmpty(nameOrId)) 
            {
                int id;
                if (int.TryParse(nameOrId, out id))
                {
                    CTagType obj = this.GetById(id);
                    if (null != obj)
                    {
                        results = new CTagTypeList(1);
                        results.Add(obj);
                        return results;
                    }
                }
            }
            */
            
            //4. Exit early if remaining (non-index) filters are blank
            if (string.IsNullOrEmpty(nameOrId)) return results; 
            
            //5. Manually search each record using custom match logic, building a shortlist
            CTagTypeList shortList = new CTagTypeList();
            foreach (CTagType i in results)
                if (Match(nameOrId, i))
                    shortList.Add(i); 
            return shortList;
        }
        //Manual Searching e.g for string-based columns i.e. anything not indexed (add more params if required)
        private bool Match(string name, CTagType obj)
        {
            if (!string.IsNullOrEmpty(name)) //Match any string column
            {
                if (null != obj.TypeName && obj.TypeName.ToLower().Contains(name))   return true;
                return false;   //If filter is active, reject any items that dont match
            }
            return true;    //No active filters (should catch this in step #4)
        }
        #endregion

        #region Cloning
        public CTagTypeList Clone(CDataSrc target) //, int parentId)
        {
            //No Transaction
            if (target is CDataSrcRemote)
                return Clone(target, null); //, parentId);

            //Transaction
            using (IDbConnection cn = target.Local.Connection())
            {
                IDbTransaction tx = cn.BeginTransaction();
                try
                {
                    CTagTypeList clone = Clone(target, tx); //, parentId);
                    tx.Commit();
                    return clone;
                }
                catch
                {
                    tx.Rollback();
                    throw;
                }
            }
        }
        public CTagTypeList Clone(CDataSrc target, IDbTransaction txOrNull) //, int parentId)
        {
            CTagTypeList list = new CTagTypeList(this.Count);
            foreach (CTagType i in this)
                list.Add(i.Clone(target, txOrNull)); //, parentId));  *Child entities must reference the new parent
            return list;
        }
        #endregion
        
        #region Export to Csv
        //Web - Need to add a project reference to System.Web, or comment out these two methods
        public void ExportToCsv(HttpResponse response) { ExportToCsv(response, "TagTypes.csv"); }
        public void ExportToCsv(HttpResponse response, string fileName)
        {
            CDataSrc.ExportToCsv(response, fileName); //Standard response headers
            StreamWriter sw = new StreamWriter(response.OutputStream);
            ExportToCsv(sw);
            sw.Flush();
            response.End();
        }

        //Non-web
        public void ExportToCsv(string filePath)
        {
            StreamWriter sw = new StreamWriter(filePath);
            ExportToCsv(sw);
            sw.Close();
        }

        //Logic
        protected void ExportToCsv(StreamWriter sw)
        {
            string[] headings = new string[] {"TypeId", "TypeAppId", "TypeName", "TagIsOneToOne"};
            CDataSrc.ExportToCsv(headings, sw);
            foreach (CTagType i in this)
            {
                object[] data = new object[] {i.TypeId, i.TypeAppId, i.TypeName, i.TagIsOneToOne};
                CDataSrc.ExportToCsv(data, sw);
            }
        }
		#endregion


		public new void Add(CTagType item)
		{
			if (null != _index && !_index.ContainsKey(item.TypeId))
				_index[item.TypeId] = item;
			_indexByAgIsOneToOne = null;
			_indexByAppId = null;

			base.Add(item);
		}
		public new void Remove(CTagType item)
		{
			if (null != _index && _index.ContainsKey(item.TypeId))
				_index.Remove(item.TypeId);
			_indexByAgIsOneToOne = null;
			_indexByAppId = null;
			base.Remove(item);
		}
	}
}
